package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.LoginAnnotation;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 甘静斌 on 2020-08-09 11:18
 */

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取浏览器上传来的请求头中携带的token
        String token = request.getHeader("token");
        //跨域协议
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //判断controller中是否有贴LoginAnnotation的注解
        HandlerMethod hm = (HandlerMethod)handler;
        //在redis中拿到token
        UserInfo user = userInfoRedisService.getUserByToken(token);
        if (hm.hasMethodAnnotation(LoginAnnotation.class)){

            //判断redis中是否有token
            if (user == null){

                //没登录的话
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }

        return true;
    }
}
